<?php
require_once ("../utils/ConnectionFactory.php");
require_once ("../persistance/data/ArticleDO.php");

/**
 *
 * CRUD pour les articles
 * @author Quentin Laujac, Charles Hurtevnent
 *
 */
class ArticleDAO {

	/**
	 * donne la liste des articles
	 */
	public function getListArticleDO() {
		$connection = ConnectionFactory::getConnection ();
		$reponse = $connection->query ( "SELECT * FROM article ORDER BY code_type_art asc" );

		if ($reponse == null || $reponse->rowCount () == 0) {
			return null;
		}

		$listArticleDO = new ArrayObject ();
		while ( $donnee = $reponse->fetch () ) {
			$articleDO = $this->setArticleDO ( $donnee );
			$listArticleDO->append ( $articleDO );
		}
		return $listArticleDO;
	}

	/**
	 * retourne un articleDO en fonction de son id
	 */
	public function getArticleDO($numeroArticle) {
		$connection = ConnectionFactory::getConnection ();
		$reponse = $connection->query ( "SELECT * FROM article WHERE num_art =" . $numeroArticle );

		if ($reponse == null || $reponse->rowCount () == 0) {
			return null;
		}

		$donnee = $reponse->fetch ();
		$articleDO = $this->setArticleDO ( $donnee );

		return $articleDO;
	}

	/**
	 * insert un produit dans la base
	 */
	public function insertArticleDO(ArticleDO $articleDO) {
		$connection = ConnectionFactory::getConnection ();

		$req = $connection->prepare("INSERT INTO article(num_art, libelle, pu, qte_dispo, code_type_art) VALUES (:num_art, :libelle, :pu, :qte_dispo, :code_type_art)");
		$req->execute(array(
			'num_art' => $articleDO->getNumArticle(),
			'libelle' => $articleDO->getLibelle(),
			'pu' => $articleDO->getPrixUnitaire(),
			'qte_dispo' => $articleDO->getQuantiteDisponible(),
			'code_type_art' => $articleDO->getCodeTypeArticle()
		));
	}

	/**
	 * update la quantite d'article disponible d'un produit dans la base
	 */
	public function updateQuantiteDisponibleArticleDO(ArticleDO $articleDO) {
		$connection = ConnectionFactory::getConnection ();
		$req = $connection->prepare("UPDATE article SET qte_dispo = :qte_dispo WHERE num_art = :num_art");
		$req->execute(array(
			'num_art' => $articleDO->getNumArticle(),
			'qte_dispo' => $articleDO->getQuantiteDisponible(),
		));
	}

	private function setArticleDO($donnee) {
		$articleDO = new ArticleDO ();
		$articleDO->setCodeTypeArticle ( $donnee ['code_type_art'] );
		$articleDO->setLibelle ( $donnee ['libelle'] );
		$articleDO->setNumArticle ( $donnee ['num_art'] );
		$articleDO->setPrixUnitaire ( $donnee ['pu'] );
		$articleDO->setQuantiteDisponible ( $donnee ['qte_dispo'] );
		return $articleDO;
	}
}
?>





